﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VerifyArgs;
using System.ComponentModel;

namespace Corvus
{
    [TypeConverter(typeof(AggregateRootTypeConverter))]
    public class EntityReference<TAggregateRoot> : EntityReference, IEntityReference<TAggregateRoot>
        where TAggregateRoot : class, IAggregateRoot
    {

        private IRepository<TAggregateRoot> _repository;
        private TAggregateRoot _instance;

        /// <summary>
        /// Repository should be injected 
        /// </summary>
        /// <param name="repository"></param>
        public EntityReference(IRepository<TAggregateRoot> repository)
        {
            Verify.Args(new { repository }).NotNull();
            _repository = repository;
        }

        /// <summary>
        /// Repository should be injected and instance is set on assignment (from TypeConverter)
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="instance"></param>
        public EntityReference(TAggregateRoot instance)
        {
            Verify.Args(new { instance }).NotNull();
            _instance = instance;
            Id = instance.Id;
        }

        public TAggregateRoot Instance
        {
            get
            {
                if (_instance == null || _repository != null)
                {
                    _instance = _repository.First(ag => string.Equals(ag.Id, Id, StringComparison.OrdinalIgnoreCase));
                }
                return _instance;

            }
        }
    }
}
